﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dln.Handler;
using Dln.Common;
using Dln.Common.Helper;
using Dln.Model;
using Dln.Common.WxPayAPI;
using System.Windows;

public partial class Page_AutoRun_Contact : Page
{
    protected string AppId = CommonHelper.GetAppSettings("AppID");
    protected string AppSecret = CommonHelper.GetAppSettings("AppSecret");
    protected string strOpenId = "";
    protected string name = "";

    public string GetAuthOpenId()
    {
        string code = DNTRequest.GetString("CODE");


        if (!String.IsNullOrEmpty(code) && code != "authdeny")
        {
            string json = RequestHelper.SendGet(String.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", AppId, AppSecret, code));
            if (!String.IsNullOrEmpty(json))
            {
                try
                {
                    OAuthConfig oAuthConfig = JSONHelper.FromJson<OAuthConfig>(json);
                    if (oAuthConfig != null)
                    {
                        strOpenId = oAuthConfig.openid;
                        Response.Redirect("http://www.healthyperson.cn:8090/login.aspx?openid=" + strOpenId);
                    }
                    else
                    {
                        strOpenId = "";
                    }
                }
                catch (Exception ex)
                {
                    strOpenId = "";
                }
            }
        }
        else
        {
            string strUrl = Request.RawUrl.ToString();
            //string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}%2fpage%2fCommon%2fWeixinRequestPage.aspx%3ffrom%3d{2}&response_type=code&scope=snsapi_userinfo&state=GetOpenid#wechat_redirect ", AppId, Server.UrlEncode(CommonHelper.GetAppSettings("mainurl")), Server.UrlEncode(strUrl));

            var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}%2FPage%2FAutoRun%2FContact.aspx&response_type=code&scope=snsapi_base&state=test#wechat_redirect", AppId, CommonHelper.GetAppSettings("mainurl").Replace(@"://", "%3A%2F%2F"));
            Response.Redirect(url);

        }
        return strOpenId;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        GetAuthOpenId();
    }

}